using GLib;
using Sqlite;
using Gee;

namespace vSqlite{
	public errordomain SQLerror{
		exec_error
	}
	
	public class vDatabase : Object{
		Database SQLdb;
		
		public vDatabase(string file){
			Sqlite.config (Sqlite.Config.SERIALIZED);
			Database.open (file, out SQLdb);
		}
		
		private Gee.ArrayList<string> SQLtasks = new Gee.ArrayList<string>();

		int callback (int n_columns, string[] values, string[] column_names){

			ret.resize(ret.length + n_columns);
			for (int q = 0; q < n_columns; q++){
				ret[q + ret.length - n_columns] = values[q];
			}
			
			return 0;
		}


		
		string[] ret;
		public string[] exec(string sql) throws SQLerror{
			lock (SQLdb) {
				Sqlite.Statement stmt = null;
				SQLdb.prepare_v2 (sql, -1, out stmt, null);

				ret = new string[0];

				int cols, col;
				int rc = 0;
				cols = stmt.column_count();

				do {
					rc = Sqlite.BUSY;
					while (rc == Sqlite.BUSY){
						rc = stmt.step();
					}
					switch (rc) {
						case Sqlite.DONE:
							break;
						case Sqlite.ROW:
							for (col = 0; col < cols; col++) {
								ret += stmt.column_text(col);
							}
							break;
						default:
							throw new SQLerror.exec_error(rc.to_string () + ": " +  SQLdb.errmsg ()); //error ("SQL Error (" +  rc.to_string () + "): " +  SQLdb.errmsg ());
					}
				} while (rc == Sqlite.ROW);

				return ret;
			}
			/*int errc = Sqlite.BUSY;
			while (errc == Sqlite.BUSY){
				ret = new string[0];
				SQLdb.exec(sql, callback);
				errc = SQLdb.errcode();
				if (errc == Sqlite.BUSY)
					Thread.usleep (10 * 1000);
				else if (errc != 0)
					error("SQL error: " + SQLdb.errmsg () + "\nwhen executing: >" + sql + "<\n");
			}
			return ret;*/
		}

	}
}
